﻿using B.R.RabbitRoot.Infrastructure.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.R.RabbitRoot.Infrastructure.Implements
{
    /// <summary>
    /// 仓储接口
    /// </summary>
    public class Baserepository<T> : IBaserepository<T> where T : class
    {
        /// <summary>
        /// 上下文
        /// </summary>
        private readonly RabbitDbcontext db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">上下文</param>
        public Baserepository(RabbitDbcontext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.AddAsync(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeleteAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<T> GetAll()
        {
          return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity)
        {
             db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 真删除
        /// </summary>
        /// <returns></returns>
        public async Task<int> removeAsync(T entity)
        {
            db.Set<T>().Remove(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 异步查询所有数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GatAsync()
        {
            return await db.Set<T>().ToListAsync();
        }
    }
}
